package br.com.classificadosonline.servlet;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.Session;

import br.com.classificadosonline.Sistema;
import br.com.classificadosonline.nucleo.Login;
import br.com.classificadosonline.nucleo.Pessoa;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Sistema sistema = Sistema.getInstance();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String usuario = request.getParameter("usuario").toString();
		String senha = "";
		try {
			senha = Sistema.toPassword(request.getParameter("senha"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		Login login = sistema.buscarLogin(usuario);
		if ((login != null) && (login.getSenha().equals(senha))) {
			sistema.login(login);
			Pessoa pessoa = sistema.buscarPessoaPorUsuario(login.getUsuario());
			request.getSession().setAttribute("UsuarioLogado", pessoa);
			RequestDispatcher dispatcher = null;
			if (sistema.buscarTipoPorCodigo(pessoa.getcodTipo()).getDescricao().equalsIgnoreCase("Anunciante")) 
				dispatcher = request.getRequestDispatcher("restrito/anunciante/anunciante.jsp");
			else if (sistema.buscarTipoPorCodigo(pessoa.getcodTipo()).getDescricao().equalsIgnoreCase("Administrador"))
				dispatcher = request.getRequestDispatcher("restrito/administrador/administrador.jsp");
			//dispatcher = request.getRequestDispatcher("/anunciante.jsp");
			dispatcher.forward(request, response);
			return;
		}	
	}
}
